package org.example.shop.service.impl;

import org.example.shop.dao.GoodsDao;
import org.example.shop.dao.OrderDao;
import org.example.shop.dao.OrderGoodDao;
import org.example.shop.pojo.Goods;
import org.example.shop.pojo.OrderGood;
import org.example.shop.pojo.UserOrder;
import org.example.shop.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private OrderGoodDao orderGoodDao;

    /**
     * 下订单 不考虑高并发
     *
     * @param goodsId
     * @param buyCount
     * @param uid
     * @return
     */
    @Transactional
    @Override
    public UserOrder buy(Long goodsId, int buyCount, int uid) {
        Optional<Goods> goodsOptional = goodsDao.findById(goodsId);
        if (!goodsOptional.isPresent()) {
            throw new RuntimeException("购买的商品不存在或者已下架");
        }
        Goods g = goodsOptional.get();
        // 判断库存
        if (g.getStock() < buyCount) {
            throw new RuntimeException("购买的商品库存不足");
        }
        // 新增订单
        UserOrder order = new UserOrder();
        order.setUid(uid);
        order.setAmount(g.getPrice() * buyCount);
        orderDao.save(order);
        // 将订单和商品进行关联
        saveOrderGoods(order, g, buyCount);
        // 减库存
        g.setStock(g.getStock() - buyCount);
        goodsDao.save(g);
        return order;
    }

    public OrderGood saveOrderGoods(UserOrder order, Goods g, int buyCount) {
        OrderGood og = new OrderGood();
        og.setGoodsId(g.getId());
        og.setOrderId(order.getId());
        og.setPrice(g.getPrice());
        og.setCount(buyCount);
        og.setTotalPrice(g.getPrice() * buyCount);
        return orderGoodDao.save(og);
    }
}
